<?php
class Email_IndexController  extends Zendvn_Controller_Action{
	
	
	public function init()
	{
		parent::init();
				
	}
	
	public function  indexAction(){
		
		$this->view->main = FALSE;
		
		if($this->getRequest()->isPost()){
		
			$idchanel = @$_POST["idchanel"];
			
			
			
			if ($idchanel != ""){
				$storage = new Zend_Auth_Storage_Session();
				$data = $storage->read();
				
			
				$chanel_follow = new Chanel_Model_FollowChanel();				
				$list_chanel_followed = $chanel_follow->listChanelByFollowed($idchanel);
				
				
	
				foreach( $list_chanel_followed as $key => $item){
								
					// Send mail Channel when user post feed
					
					$storage = new Zend_Auth_Storage_Session();
					$data = $storage->read();
					
					$auth = new Registration_Model_Auth();
					
					$user = $auth->getItemById($item["follower"]);
					
					if($user && $user["id"] != $data->id){
	
						$chanel = new Chanel_Model_Index();
						
						$chanel_item = $chanel->getChanelById($idchanel);
											
						$this->checkSendMail($user,$chanel_item);
						
					}
					
				}
				
			}
		}
	}
	
	public function checkSendMail($user,$chanel_item){
		
		$auth = new Registration_Model_Auth();
		$feed = new Feed_Model_Index();
		
		$time_last_login = strtotime($user["time_last_login"]);
		$time_send_mail = strtotime($user["time_send_mail"]);
		
		// check time send mail va time hien tai
		$now = strtotime(date('Y-m-d h:i:s',time()));		
		
		$days_now_sendmail = abs($now - $time_send_mail);
			

		if($days_now_sendmail < 24*3600){
			return;
		}
				

		$secs = $time_last_login - $time_send_mail;// == <seconds between the two times>
		$days = $secs / 86400;
		
		// time last login < time send mail
		if($days < 0){
						
			if(abs($days) >  (int)$user["number_day_send"]){

				
				
				//update time send mail, number day send
				
				if((int)$user["number_day_send"] < 8){
					
					//send mail
					
					$feed->sendEmail($user,$chanel_item);
					
					$number_day_send = (int)$user["number_day_send"] * 2;
					
				}else{
					$number_day_send = 8;
				}
				
				$arr = array(
				"id"=>$user["id"],
				"time_send_mail"=>date('Y-m-d h:i:s',time()),					
				"number_day_send"=>(string)$number_day_send,				
				);
				
				$auth->updateProfile($arr);
				
			}
		}
		else{ // time last login  > time send mail
			
				//send mail
				
				$feed->sendEmail($user,$chanel_item);
				
				//update time send mail, number day send
				
				if((int)$user["number_day_send"] > 1){

					$number_day_send = (int)$user["number_day_send"] / 2;
					
				}else{
					$number_day_send = 1;
				}
				
				$arr = array(
				"id"=>$user["id"],
				"time_send_mail"=>date('Y-m-d h:i:s',time()),					
				"number_day_send"=>(string)$number_day_send,				
				);
				
				$auth->updateProfile($arr);
			
			
		}
	}
	
	
}